<template>
  <ele-page>
    <h2>{{ company }} - {{ belongsDate }} 工资表</h2>
    <el-button
      type="success"
      style="margin-bottom: 15px"
      @click="exportExcel"
      :icon="DocumentCopy"
    >
      导出表格
    </el-button>
    <ele-card v-for="position in tableList" :key="position.position_id">
      <template #header>
        {{ position.positionTitle }}
        <el-button
          type="warning"
          size="small"
          style="margin-left: 5px"
          @click="openDuiZhang(position)"
        >
          按天对账
        </el-button>
        <span class="mini-title">总垫付：</span>
        <span class="val" style="margin-right: 10px">
          <span class="amount-integer">{{ position.totalAmount }}</span>
          <span class="currency">元</span>
        </span>
        <span class="mini-title">额外工资：</span>
        <span class="val" style="margin-right: 10px">
          <span class="amount-integer">{{ position.totalOtherAmount }}</span>
          <span class="currency">元</span>
        </span>
        <span class="mini-title">对账工资：</span>
        <span class="val" style="margin-right: 10px">
          <span class="amount-integer">{{ position.totalHoursAmount }}</span>
          <span class="currency">元</span>
        </span>
        <span class="mini-title">对账工时：</span>
        <span class="val" style="margin-right: 10px">
          <span class="amount-integer">{{ position.totalQuantity }}</span>
          <span class="currency"></span>
        </span>
        <span class="mini-title">对账价格：</span>
        <span class="val" style="margin-right: 10px">
          <span class="amount-integer">{{ position.companyPrice }}</span>
          <span class="currency"></span>
        </span>
        <span class="mini-title">毛利：</span>
        <span class="val" style="margin-right: 10px">
          <span class="amount-integer">{{ position.totalProfit }}</span>
          <span class="currency">元</span>
        </span>
      </template>
      <div>
        <hot-table
          :height="34 * position.datas.length + 51"
          ref="tableRef"
          :data="position.datas"
          :colHeaders="columns[position.positionId]"
          :settings="tableSettings"
          :cells="setReadOnlyCells"
          :mergeCells="mergeCellsData[position.positionId]"
          :afterOnCellMouseDown="
            (event, coords, td) => onCellClick(event, coords, td, position)
          "
        />
      </div>
    </ele-card>
    <!-- 学生详情 -->
    <Detail v-model="showDetail" :student-id="currentId" />
    <OtherSalary v-model="showOtherSalaryAll" :data="current" />
    <DuiZhang v-model="showDuiZhang" :data="current" />
  </ele-page>
</template>

<script setup>
  import { onMounted, ref, unref, watch } from 'vue';
  import { DocumentCopy } from '@element-plus/icons-vue';
  import { getSalaryDeatilTable, exportSalaryDetailTable } from '@/api/company';
  import Detail from '@/views/student/components/detail.vue';
  import OtherSalary from './components/other-salary.vue';
  import DuiZhang from './components/duizhang.vue';
  import { useRouter } from 'vue-router';
  import { EleMessage } from 'ele-admin-plus/es';
  import { HotTable } from '@handsontable/vue3';
  import { registerAllModules } from 'handsontable/registry';
  import 'handsontable/styles/handsontable.min.css';
  import 'handsontable/styles/ht-theme-main.min.css';
  registerAllModules();

  const { currentRoute } = useRouter();
  const ROUTE_PATH = '/company/position';

  /** 企业id */
  const companyId = ref(0);
  const company = ref('');

  /** 所属月份 */
  const belongsDate = ref('');

  const tableList = ref([]);
  const columns = ref([]);
  const mergeCellsData = ref([]);
  const fetchData = () => {
    const loading = EleMessage.loading({ message: '正在加载中..', mask: true });
    const { query } = unref(currentRoute);
    companyId.value = Number(query.id);
    belongsDate.value = String(query.belongs_date);
    company.value = String(query.company);

    getSalaryDeatilTable({
      company_id: companyId.value,
      belongs_date: belongsDate.value
    })
      .then((res) => {
        loading.close();
        tableList.value = res.tableList;
        columns.value = res.columns;
        mergeCellsData.value = res.mergeCellsData;
        console.log(res);
      })
      .catch((e) => {
        loading.close();
        EleMessage.error(e.message);
      });
  };

  const tableRef = ref();

  const tableSettings = ref({
    hiddenColumns: {
      copyPasteEnabled: true,
      indicators: true,
      columns: [0, 1]
    },
    fixedRowsTop: 0, // 冻结第一行（表头）
    fixedColumnsLeft: 9, // 冻结前五列
    // enable the column menu
    dropdownMenu: true,
    autoColumnSize: true,
    manualColumnResize: true,
    manualRowResize: true,

    licenseKey: 'non-commercial-and-evaluation'
  });

  const setReadOnlyCells = (row, col) => {
    if (col < 8) {
      if (col == 3) {
        return { readOnly: true, className: 'highlight-row' }; // 总应回
      }

      return { readOnly: true }; // 前5列 只读
    }

    const groupIndex = Math.floor(row / 3);
    if (groupIndex % 2 === 0) {
      return { className: 'interval-row' };
    }
  };

  // 点击单元格触发
  const onCellClick = (event, coords, td, currentTableDatas) => {
    if (coords.row >= 0 && coords.col >= 0) {
      let row = coords.row;
      let col = coords.col;
      if (col == 5) {
        // 额外工资列

        openOtherSalaryAll(
          currentTableDatas.datas[row],
          currentTableDatas.positionId,
          currentTableDatas.positionTitle
        );
      }
      if (row % 3 == 1 && col > 8) {
        // 垫付金额
        // openSalaryDetail();
      }
      if (col == 2) {
        showStudentDetail(currentTableDatas.datas[row][0]);
      }
    }
  };

  const current = ref();
  const currentId = ref(0);
  /** 学生详情 */
  const showDetail = ref(false);
  const showStudentDetail = (id) => {
    currentId.value = id;
    showDetail.value = true;
  };

  onMounted(() => {
    fetchData();
  });
  /** 重新加载 */
  const reload = () => {
    fetchData();
  };
  /** 额外工资 */
  const showOtherSalaryAll = ref(false);
  const openOtherSalaryAll = (rowData, positionId, positionTitle) => {
    let memberId = rowData[0];
    let realname = rowData[2];

    current.value = {
      realname,
      memberId,
      companyId: companyId.value,
      belongsDate: belongsDate.value,
      positionId,
      positionTitle
    };

    showOtherSalaryAll.value = true;
  };
  const showDuiZhang = ref(false);
  const openDuiZhang = (item) => {
    const { query } = unref(currentRoute);
    companyId.value = Number(query.id);
    belongsDate.value = String(query.belongs_date);
    company.value = String(query.company);
    current.value = {
      company_id: companyId.value,
      belongs_date: belongsDate.value,
      company: company.value,
      position_id: item.positionId,
      position_title: item.positionTitle
    };
    showDuiZhang.value = true;
  };

  /** 导出表格 */
  const exportExcel = () => {
    const loading = EleMessage.loading({ message: '正在加载中..', mask: true });

    exportSalaryDetailTable({
      company_id: companyId.value,
      belongs_date: belongsDate.value
    })
      .then((res) => {
        loading.close();
        window.open(res);
      })
      .catch(() => {
        loading.close();
      });
  };

  watch(
    currentRoute,
    (route) => {
      if (unref(route).path !== ROUTE_PATH) {
        return;
      }
      reload();
    },
    { immediate: true }
  );
</script>
<style scoped>
  .tools {
    margin-bottom: 16px;
  }
  .sum {
    height: 25px;
    line-height: 25px;
    padding-bottom: 12px;
  }
  .val {
    font-size: 24px;
    color: #f56c6c;
    font-weight: bold;
  }
  .excel-table {
    overflow: auto;
  }
  :deep(.htCore th) {
    padding: 10px 5px !important; /* 调整单元格内边距 */
  }
  :deep(.htCore td) {
    height: 25px;
    line-height: 25px;
    padding: 4px 8px;
  }
  :deep(.highlight-row) {
    background-color: bisque !important;
    font-weight: bold;
  }
  :deep(.interval-row) {
    background-color: rgb(237, 236, 236) !important;
  }
  :deep(.dark-row) {
    background-color: rgb(237, 236, 236) !important;
  }
  :deep(.success-row) {
    background-color: rgb(236, 250, 239) !important;
  }
  :deep(.danger-row) {
    color: red !important;
  }

  :deep(.handsontable th:nth-child(2)) {
    border-inline-start-width: 0px;
  }

  :deep(.tac) {
    text-align: center;
  }

  :deep(.htCore) {
    text-align: center;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  :deep(.pass-row) {
    background-color: rgb(221, 250, 228) !important;
  }
  :deep(.total-col) {
    width: 87px;
  }
  :deep(.tel-col) {
    width: 95px;
  }
  .amount-integer {
    font-size: 24px;
    font-weight: bold;
    color: #f56c6c;
  }

  .amount-decimal {
    font-size: 14px;
    font-weight: normal;
    color: #f56c6c;
  }

  .currency,
  .unit {
    font-size: 14px;
    font-weight: normal;
    color: #333;
  }
  .hot-table-div {
    width: 100%;
    overflow: auto;
  }
  .mini-title {
    font-size: 14px;
    font-weight: normal;
    margin-left: 8px;
  }
</style>
